package com.test.file;

import java.io.*;


public class FileOps {
    public static void read_file() throws IOException {
        // 1. 读取文件
        // Reader 类因为是抽象类，所以不能直接创建对象，需要使用它的子类 FileReader 来创建对象
        Reader reader = new FileReader(new File("src/test/resources/login.json"));
        BufferedReader bf = new BufferedReader(reader);
        // 通过BufferedReader 类的 readLine() 方法读取文件
        System.out.println(bf.readLine());
        System.out.println(bf.readLine());

        for (String line; (line = bf.readLine()) != null; ) {
            System.out.println(line);
        }

        String line;
        while ((line = bf.readLine()) != null) {
            System.out.println(line);
        }
        bf.close();
    }

    public static void write_file() throws IOException {
        // 2. 写入文件
        Writer writer = new FileWriter(new File("src/test/resources/write.txt"));
        // 通过BufferedWriter 类的 write() 方法写入文件
        BufferedWriter bw = new BufferedWriter(writer);
        bw.write("hello world");
        bw.newLine();
        bw.newLine();
        bw.write("line 3");
        bw.flush();
        bw.close();
    }

    public static void read_png_file() throws IOException {
        // 3. 读取图片文件
        FileInputStream fileInputStream = new FileInputStream(new File("src/test/resources/flower.jpg"));
        byte[] arr = new byte[1024];
        int count = 0;
        while (fileInputStream.read(arr) != -1) {
            count += 1;
        }
        System.out.println(count);
        fileInputStream.close();
    }

    public static void write_png_file() throws IOException {
        // 4. 写入图片文件
        // 通过读写来复制图片文件
        FileOutputStream fileOutputStream = new FileOutputStream(new File("src/test/resources/flower2.jpg"));
        FileInputStream fileInputStream = new FileInputStream(new File("src/test/resources/flower.jpg"));
        byte[] arr = new byte[1024];
        while (fileInputStream.read(arr) != -1) {
            fileOutputStream.write(arr);
        }
        fileOutputStream.flush();
        fileOutputStream.close();
        fileInputStream.close();
    }

    public static void main(String[] args) throws IOException {
        read_file();
        write_file();
        read_png_file();
        write_png_file();
    }
}
